import React, { useState } from 'react';
import { useDispatch } from 'react-redux';
import { addAction } from '../store/action/todo';

export default function Header() {
  const dispatch = useDispatch();
  // input 内容的维护，与全局无关，建议自己组件维护自己的状态即可
  const [name, setName] = useState('');
  const handleKeyUp = (e) => {
    // console.log('e -----> ', e);
    if (!name.trim()) {
      return alert('暂无内容');
    }
    if (e.key === 'Enter') {
      dispatch(addAction(name));
      setName('');
    }
  };
  return (
    <header className="header">
      <h1>todos</h1>
      <input
        value={name}
        onChange={(e) => setName(e.target.value)}
        onKeyUp={handleKeyUp}
        className="new-todo"
        placeholder="需要做什么"
        autoFocus
      />
    </header>
  );
}
